package com.dev.module_zqc_sleep.utils

import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import com.dev.module_ui_composable.utils.ToastUtils
import java.io.File
import java.util.Locale

object FileUtils {

    fun openFile(context: Context, filePath: String) {
        val file = File(filePath)
        if (!file.exists()) {
            ToastUtils.showShortToast(context, "文件不存在")
            return
        }

        val uri: Uri =
            FileProvider.getUriForFile(context, "${context.packageName}.fileProvider", file)

        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(uri, getMimeType(filePath))
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        try {
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            ToastUtils.showShortToast(context, "没有找到适合打开此文件的应用")
        }
    }

    fun openFileWithUri(context: Context, fileUri: Uri) {
        val intent = Intent(Intent.ACTION_VIEW).apply {
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
        }

        // 设置Intent的Data和Type，通过查询文件Uri来获取MIME类型
        val mimeType = context.contentResolver.getType(fileUri)
        if (mimeType != null) {
            intent.setDataAndType(fileUri, mimeType)
        } else {
            ToastUtils.showShortToast(context, "无法确定文件类型或文件被删除")
            return
        }

        // 尝试启动Activity来打开文件
        try {
            context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            ToastUtils.showShortToast(context, "没有找到适合打开此文件的应用")
        }
    }

    /**
     * 调用系统分享
     */
    fun shareFile(context: Context, filePath: String) {
        val file = File(filePath)
        if (!file.exists()) {
            // 文件不存在
            ToastUtils.showShortToast(context, "文件不存在")
            return
        }

        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileProvider", file)

        val shareIntent = Intent().apply {
            action = Intent.ACTION_SEND
            putExtra(Intent.EXTRA_STREAM, uri)
            type = context.contentResolver.getType(uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }

        val chooser = Intent.createChooser(shareIntent, "文件分享")
        context.startActivity(chooser)
    }

    private fun getMimeType(filePath: String): String {
        val extension = MimeTypeMap.getFileExtensionFromUrl(filePath)
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "*/*"
    }

    fun renameFile(filePath: String, newFileName: String): Boolean {
        val oldFile = File(filePath)
        if (!oldFile.exists()) {
            // 文件不存在
            return false
        }

        val newFile = File(oldFile.parent, newFileName)
        if (newFile.exists()) {
            // 如果新文件名已存在
            return false
        }

        return oldFile.renameTo(newFile)
    }

    fun deleteFile(filePath: String): Boolean {
        val file = File(filePath)
        if (file.exists()) {
            return file.delete()
        }
        return false
    }

    fun deleteFiles(filePaths: List<String>): Boolean {
        var allDeleted = true
        for (filePath in filePaths) {
            val file = File(filePath)
            if (file.exists() && !file.delete()) {
                allDeleted = false
            }
        }
        return allDeleted
    }

    fun getDirOrFileSize(path: String): String {
        val file = File(path)
        if (!file.exists()) {
            return ""
        }
        return if (file.isFile) {
            formatFileSize(file.length())
        } else {
            val files = file.listFiles()
            var size: Long = 0
            for (f in files!!) {
                size += if (f.isDirectory) 0 else f.length()
            }
            formatFileSize(size)
        }
    }

    fun formatTime(size: Int): String {
        val time: String = if (size < 60) {
            String.format(Locale.getDefault(), "00:%02d", size % 60)
        } else if (size < 3600) {
            String.format(Locale.getDefault(),"%02d:%02d", size / 60, size % 60)
        } else {
            String.format(Locale.getDefault(), "%02d:%02d:%02d", size / 3600, size % 3600 / 60, size % 60)
        }
        return time
    }

    /**
     * 格式化文件大小
     */
    fun formatFileSize(size: Long): String {
        val kiloByte: Long = 1024
        val megaByte = kiloByte * 1024
        val gigaByte = megaByte * 1024
        val teraBytes = gigaByte * 1024

        return when {
            size < kiloByte -> "${size}B"
            size < megaByte -> "${size / kiloByte}KB"
            size < gigaByte -> "${String.format(Locale.getDefault(), "%.2f", size / megaByte.toDouble())}MB"
            size < teraBytes -> "${String.format(Locale.getDefault(), "%.2f", size / gigaByte.toDouble())}GB"
            else -> "${String.format(Locale.getDefault(), "%.2f", size / teraBytes.toDouble())}TB"
        }
    }

}